<?php

namespace App\Jobs;

use App\Order;
use App\Services\ExpressService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class DeliveryJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data=$data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $orders=Order::whereIn('id',$this->data)->get();
        $orders=$orders->groupBy('address_phone_number');
        $service=new ExpressService();
        foreach ($orders as $key=>$value){
            $arr=collect([]);
            foreach ($value as $k=>$v){
                $arr->push($v);
            }
            $arr1=$arr->pluck("id");
            $tracking_no=$service->add($value[0]);
            Order::whereIn('id',$arr1)->update(['tracking_no'=>$tracking_no,'delivery_name'=>"顺丰快递",'delivery_id'=>'SF']);
            dispatch(new ReceivingJob($arr1->all()))->delay(Carbon::now()->addDays(7));
        }
    }
}
